package com.xxmw.transaction.common.utils.bourse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxmw.transaction.common.excep.service.TransactionException;
import com.xxmw.transaction.common.utils.Constant;
import com.xxmw.transaction.common.utils.HmacUtil;
import com.xxmw.transaction.common.utils.HuoBiGZipUtils;
import com.xxmw.transaction.common.utils.http.HttpClientUtil;
import com.xxmw.transaction.enumeration.HuobiSymbolEnum;
import com.xxmw.transaction.enumeration.TradeTypeEnum;
import com.xxmw.transaction.model.app.BourseApi;
import com.xxmw.transaction.model.app.BourseOrder;
import com.xxmw.transaction.vo.BalanceVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author luowenliang
 * @since 2020/2/5 17:16
 * https://huobiapi.github.io/docs/spot/v1/cn/#5ea2e0cde2
 */
@Slf4j
@Component
public class HuobiUtil {

    private static final String NETWORK_PROTOCOL = "https://";

    private static final String DOMAIN = "api.huobi.pro";

    private static final String USDT_BALANCE_PATH = "/v1/account/accounts/XXXX/balance";

    /**
     * 火币获取最新交易
     */
    private static final String TRADE_PATH = "/trade?symbol=";

    /**
     * 下单
     */
    private static final String ORDER_PATH = "/v1/order/orders/place";

    /**
     * 批量下单
     */
    private static final String BATCH_ORDER_PATH = "/v1/order/batch-orders";

    /**
     * 撤销订单 %s为火币订单号
     */
    private static final String ORDER_CANCEL_PATH = "/v1/order/orders/%s/submitcancel";

    /**
     * 订单详情 /v1/order/orders/{order-id}
     */
    private static final String ORDER_INFO_PATH = "/v1/order/orders/";

    /**
     * 获取账户信息API
     */
    private static final String ACCOUNT_PATH = "/v1/account/accounts";

    /**
     * 此接口返回所有火币全球站支持的交易对 在此接口查看交易对的最小精度和交易额
     */
    private static final String SYMBOLS_INFO_PATH = "/v1/account/accounts";

    /**
     * K线数据
     */
    private static final String KLINE_PATH = "/market/history/kline";



    /**
     * 签名方法
     */
    private static final String SIGNATURE_METHOD = "HmacSHA256";
    /**
     * 签名版本
     */
    private static final String SIGNATURE_VERSION = "2";

    private static final DateTimeFormatter HUOBI_TIME_STAMP_FORMAT = DateTimeFormatter
            .ofPattern("uuuu-MM-dd'T'HH:mm:ss");


    /**
     * 获取账户余额
     * @param api
     * @param currency usdt、btc...
     * @return
     */
    public static BalanceVo getBalance(BourseApi api, String currency) {
        JSONArray array = getBalanceArray(api);
        BalanceVo balanceVo = new BalanceVo();
        for (int i =0; i < array.size(); i ++) {
            JSONObject jsonObject = array.getJSONObject(i);
            if (jsonObject.getString("currency").equals(currency)) {
                //return jsonObject.getBigDecimal("balance");
                if (jsonObject.getString("type").equals("trade")) {
                    // 获取可用
                    balanceVo.setAvailable(jsonObject.getBigDecimal("balance"));
                }
                if (jsonObject.getString("type").equals("frozen")) {
                    // 获取冻结
                    balanceVo.setFrozen(jsonObject.getBigDecimal("balance"));
                }
            }
        }
        balanceVo.setTotal(balanceVo.getAvailable().add(balanceVo.getFrozen()));
        return balanceVo;
    }

    public static Map<String, BalanceVo> getBalance (BourseApi api, List<String> currency) {

        Map<String, BalanceVo> map = new HashMap<>(16);

        if (currency.size() <= 0) {
            return map;
        }

        for (String s : currency) {
            map.put(s, getBalance(api, s));
        }
        return map;
    }

    public static JSONArray getBalanceArray (BourseApi api) {
        Map<String, String> paramMap = new TreeMap<>();
        String path = USDT_BALANCE_PATH.replace("XXXX",String.valueOf(api.getAccountId()));
        paramMap.put("AccessKeyId", api.getAccessKey());
        paramMap.put("SignatureMethod", SIGNATURE_METHOD);
        paramMap.put("SignatureVersion", SIGNATURE_VERSION);
        paramMap.put("Timestamp", urlEncode(getTimestamp()));
        paramMap.put("account-id", String.valueOf(api.getAccountId()));
        //参数拼接
        StringBuilder paramSb = new StringBuilder();
        paramMap.entrySet().forEach(entry -> paramSb.append(entry.toString()).append("&"));
        String paramStr = paramSb.substring(0, paramSb.length() - 1);

        //参数进行签名编码
        String signature = createUrlSignature(api.getSecretKey(), Constant.RequestType.GET.name(), paramStr, path);
        String url = getRequestUrl(path) + "?" + paramStr + "&Signature=" + signature;
        String resp = HttpClientUtil.get(url);
        JSONObject json = JSONObject.parseObject(resp);
        if (json != null) {
            return json.getJSONObject("data").getJSONArray("list");
        }
        throw new TransactionException("获取火币账户余额信息异常");
    }

    /**
     * 获取火币最新成交价格
     * @param symbol 交易对 btcusdt ethusdt ...
     * @return
     * @throws Exception
     */
    public static BigDecimal huobiPrice(String symbol) throws Exception {
        String res = HttpClientUtil.get(getRequestUrl(TRADE_PATH + symbol));
        log.info("huobiPrice请求响应：{}", res);
        JSONObject json = JSONObject.parseObject(res);
        if ("ok".equals(json.getString("status"))) {
            JSONObject jsonObject = json.getJSONObject("tick");
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            JSONObject object = jsonArray.getJSONObject(0);
            BigDecimal huoibPrice = new BigDecimal(object.getString("price")).setScale(5, BigDecimal.ROUND_HALF_EVEN);
            log.info("火币汇率：{} = {}", symbol, huoibPrice);
            return huoibPrice;
        }
        throw new Exception("获取火币交易对 " + symbol + "，费率失败");
    }

    /**
     * 火币下单
     * 参数拼接请看 https://huobiapi.github.io/docs/spot/v1/cn/#c64cd15fdc
     */
    public static void order (BourseApi api, BourseOrder order) {
        log.info("【火币下单开始】");
        Map<String, String> paramMap = new TreeMap<>();

        paramMap.put("AccessKeyId", api.getAccessKey());
        paramMap.put("SignatureMethod", SIGNATURE_METHOD);
        paramMap.put("SignatureVersion", SIGNATURE_VERSION);
        paramMap.put("Timestamp", urlEncode(getTimestamp()));

        paramMap.put("account-id", api.getAccountId().toString());
        paramMap.put("symbol", order.getSymbol());
        String typeDesc = TradeTypeEnum.getDescByValue(order.getTradeType());
        paramMap.put("type", typeDesc);
        //.setScale(getScale(order.getSymbol(), 1), BigDecimal.ROUND_DOWN).toString()
        if(order.getTradeType().equals(TradeTypeEnum.BUY_MARKET.getValue())) {
            paramMap.put("amount", order.getNum().multiply(order.getPrice().add(BigDecimal.ONE)).stripTrailingZeros().toString());
        } else {
            paramMap.put("amount", order.getNum().stripTrailingZeros().toString());
        }
        //现货交易填写“spot-api” 默认现货交易
//        paramMap.put("source", "spot-api");
        if (typeDesc.contains("limit")) {
            //限价单
            paramMap.put("price", order.getPrice().setScale(getScale(order.getSymbol(), 2), BigDecimal.ROUND_DOWN).toString());
        }

        //签名参数拼接
        StringBuilder paramSb = new StringBuilder();
        paramMap.entrySet().forEach(entry -> paramSb.append(entry.toString()).append("&"));
        String paramStr = paramSb.substring(0, paramSb.length() - 1);
        log.info("json param: {}", JSON.toJSONString(paramMap));

        //参数进行签名编码
        String signature = createUrlSignature(api.getSecretKey(), Constant.RequestType.POST.name(), paramStr, ORDER_PATH);

        //POST请求URL拼接
        String url = getRequestUrl(ORDER_PATH) + "?" + paramStr + "&Signature=" + signature;
        log.info("火币下单：request url: {}, 参数：{}", url, paramMap.toString());
        //发送请求
        String res = HttpClientUtil.post(url, null,  JSON.toJSONString(paramMap));
        log.info("下单请求结果: {}", res);
        JSONObject jsonObject = JSON.parseObject(res);
        if ("ok".equals(jsonObject.get("status"))) {
            String huBiOrderNo = jsonObject.getString("data");
            order.setOutId(huBiOrderNo);
            order.setStatus(1);
        } else {
            log.error("火币下单失败：{}", res);
            order.setStatus(7);
            order.setRemark(jsonObject.getString("err-msg"));
        }
    }

    /**
     * 批量下单
     * @param api
     * @param orders
     */
    public static <T extends BourseOrder> void order (BourseApi api, List<T> orders) {

        if (null == orders || 0 == orders.size()) {
            return;
        }

        if (1 == orders.size()) {
            order(api, orders.get(0));
        }

        Map<String, String> paramMap = new TreeMap<>();

        paramMap.put("AccessKeyId", api.getAccessKey());
        paramMap.put("SignatureMethod", SIGNATURE_METHOD);
        paramMap.put("SignatureVersion", SIGNATURE_VERSION);
        paramMap.put("Timestamp", urlEncode(getTimestamp()));

        JSONArray bodyArray = new JSONArray();
        for (T order : orders) {
            String typeDesc = TradeTypeEnum.getDescByValue(order.getTradeType());
            JSONObject o = new JSONObject();
            o.put("account-id", api.getAccountId());
            o.put("symbol", order.getSymbol());
            o.put("type", typeDesc);
            o.put("amount", order.getNum());
            if (typeDesc.contains("limit")) {
                o.put("price", order.getPrice());
            }
            o.put("client-order-id", order.getId());
            o.put("source", "spot-api");
            bodyArray.add(o);
        }

        StringBuilder paramSb = new StringBuilder();
        paramMap.entrySet().forEach(entry -> paramSb.append(entry.toString()).append("&"));
        String paramStr = paramSb.substring(0, paramSb.length() - 1);
        String signature = createUrlSignature(api.getSecretKey(), Constant.RequestType.POST.name(), paramStr, BATCH_ORDER_PATH);

        String url = getRequestUrl(BATCH_ORDER_PATH) + "?" + paramStr + "&Signature=" + signature;

        String res = HttpClientUtil.post(url,  bodyArray.toJSONString());

        log.info("火币批量下单请求结果: {}", res);

        JSONObject jsonObject = JSON.parseObject(res);
        if ("ok".equals(jsonObject.get("status"))) {
            //TODO 结果未处理
            JSONArray orderArray = jsonObject.getJSONArray("data");
            //{
            //    "status": "ok",
            //    "data": [
            //        {
            //            "order-id": 61713400772,
            //            "client-order-id": "c1"
            //        },
            //        {
            //            "order-id": 61713400940,
            //            "client-order-id": "d2"
            //        }
            //    ]
            //}
            log.error("火币批量下单结果未处理");
        } else {
            log.error("火币批量下单失败");
        }
    }

    /**
     * BourseOrder order
     */
    public static void cancelOrder (BourseApi api, BourseOrder order) {
        Map<String, String> paramMap = new TreeMap<>();

        paramMap.put("AccessKeyId", urlEncode(api.getAccessKey()));
        paramMap.put("Timestamp", urlEncode(getTimestamp()));
        paramMap.put("SignatureMethod", SIGNATURE_METHOD);
        paramMap.put("SignatureVersion", SIGNATURE_VERSION);

        paramMap.put("order-id", order.getOutId());
        //签名参数拼接
        StringBuilder paramSb = new StringBuilder();
        paramMap.entrySet().forEach(entry -> paramSb.append(entry.toString()).append("&"));
        String paramStr = paramSb.substring(0, paramSb.length() - 1);
        log.info("paramStr: {}", paramStr);

        String orderPath = String.format(ORDER_CANCEL_PATH, order.getOutId());

        //参数进行签名编码
        String signature = createUrlSignature(api.getSecretKey(), Constant.RequestType.POST.name(),
                paramStr, orderPath);

        //POST请求URL拼接
        String url = getRequestUrl(orderPath) + "?" + paramStr + "&Signature=" + signature;
        String res = HttpClientUtil.post(url, null,paramStr);
        log.info("取消订单：{}", res);
    }

    /**
     * 订单详情查询
     * GET /v1/order/orders/{order-id}
     * @param api 交易所账号信息
     * @param order 订单
     */
    public static void orderInfo (BourseApi api, BourseOrder order) throws Exception {
        Map<String, String> paramMap = new TreeMap<>();

        paramMap.put("AccessKeyId", api.getAccessKey());
        paramMap.put("SignatureMethod", SIGNATURE_METHOD);
        paramMap.put("SignatureVersion", SIGNATURE_VERSION);
        paramMap.put("Timestamp", urlEncode(getTimestamp()));

        paramMap.put("order-id", order.getOutId());

        //参数拼接
        StringBuilder paramSb = new StringBuilder();
        paramMap.entrySet().forEach(entry -> paramSb.append(entry.toString()).append("&"));
        String paramStr = paramSb.substring(0, paramSb.length() - 1);
        log.info("paramStr: {}", paramStr);

        //参数进行签名编码
        String signature = createUrlSignature(api.getSecretKey(), Constant.RequestType.GET.name(), paramStr, ORDER_INFO_PATH + order.getOutId());

        String url = getRequestUrl(ORDER_INFO_PATH + order.getOutId()) + "?" + paramStr + "&Signature=" + signature;
        String resp = HttpClientUtil.get(url);
        log.info("获取火币订单详情返回数据"+resp);
        //{"status":"ok","data":{"id":71346371711,"symbol":"htusdt","account-id":3685505,"client-order-id":"","amount":"6.000000000000000000","price":"1.000000000000000000","created-at":1582631230215,"type":"buy-limit","field-amount":"0.0","field-cash-amount":"0.0","field-fees":"0.0","finished-at":0,"source":"spot-api","state":"submitted","canceled-at":0}}
        JSONObject jsonObject = JSON.parseObject(resp);
        if ("ok".equalsIgnoreCase(jsonObject.getString("status"))){
            JSONObject data = jsonObject.getJSONObject("data");
            String state = data.getString("state");
            //更新订单状态
            order.setStatus(getOrderStatus(state));
            order.setDealNum(data.getBigDecimal("field-amount"));
            order.setFee(data.getBigDecimal("field-fees"));
            if(data.getBigDecimal("field-cash-amount") != null && data.getBigDecimal("field-cash-amount").compareTo(BigDecimal.ZERO) >0 &&
                    data.getBigDecimal("field-amount") !=null) {
                order.setAvgPrice(data.getBigDecimal("field-cash-amount").divide(data.getBigDecimal("field-amount"),4, BigDecimal.ROUND_DOWN));
            }
        } else {
            throw new Exception("获取订单信息失败");
        }
    }

    /**
     * 获取现货账户id
     * spot：现货账户， margin：逐仓杠杆账户，otc：OTC 账户，point：点卡账户，super-margin：全仓杠杆账户
     * @return
     */
    public static Long accountId (String accessKey, String secretKey) {

        Long accountId = 0L;

        Map<String, String> paramMap = new TreeMap<>();
        paramMap.put("AccessKeyId", accessKey);
        paramMap.put("SignatureMethod", SIGNATURE_METHOD);
        paramMap.put("SignatureVersion", SIGNATURE_VERSION);
        paramMap.put("Timestamp", urlEncode(getTimestamp()));

        //参数拼接
        StringBuilder paramSb = new StringBuilder();
        paramMap.entrySet().forEach(entry -> paramSb.append(entry.toString()).append("&"));
        String paramStr = paramSb.substring(0, paramSb.length() - 1);
        log.info("paramStr: {}", paramStr);

        //参数进行签名编码
        String signature = createUrlSignature(secretKey, Constant.RequestType.GET.name(), paramStr, "/v1/account/accounts");

        String url = getRequestUrl(ACCOUNT_PATH) + "?" + paramStr + "&Signature=" + signature;

        String res = HttpClientUtil.get(url);
        JSONObject jsonObject = JSON.parseObject(res);
        //{"status":"ok","data":[{"id":3685505,"type":"spot","subtype":"","state":"working"},{"id":3738096,"type":"otc","subtype":"","state":"working"},{"id":6385272,"type":"point","subtype":"","state":"working"}]}
        if ("ok".equals(jsonObject.get("status"))) {
            //暂时只拿现货账户
            JSONArray accountArray = jsonObject.getJSONArray("data");
            for (Object o : accountArray) {
                JSONObject account = (JSONObject) o;
                if ("spot".equals(account.get("type"))) {
                    accountId = account.getLong("id");
                    break;
                }
            }
        }
        return accountId;
    }

    public static void symbolsInfo () {
        String url = getRequestUrl(SYMBOLS_INFO_PATH); //+ "?" + paramStr + "&Signature=" + signature
        String res = HttpClientUtil.get(url);
        log.info(res);
    }

    /**
     * 获取当天0点的价格，用于计算涨幅
     * 可以把全部币种的值启动时计算好，存redis
     * @return
     */
    public static String dayOpen (String symbol) {

        Calendar now = Calendar.getInstance();
        int size = now.get(Calendar.HOUR_OF_DAY) + 1;

        String url = getRequestUrl(KLINE_PATH) + "?symbol=" + symbol + "&period=60min&size=" + size;
        String res = HttpClientUtil.get(url);

        JSONArray data = JSON.parseObject(res).getJSONArray("data");
        JSONObject o = data.getJSONObject(data.size() - 1);

        Long id = o.getLong("id");
        Date date = new Date(id * 1000);
        log.info("时间:{},价格：{}", date, o.getString("open"));
        return o.getString("open");
    }

    /**
     * 签名并url编码
     * @param secretKey 火币账户secretKey
     * @param paramStr 已按ASSIC码排序的参数字符串
     * @param path 请求路径
     * @param requestType POST GET
     * @return
     */
    public static String createUrlSignature (String secretKey, String requestType, String paramStr, String path) {
        StringBuilder signSb = new StringBuilder();
        signSb.append(requestType).append("\n").append(DOMAIN).append("\n").append(path).append("\n").append(paramStr);
        log.info("signStr: {}", signSb.toString());
        String s = HmacUtil.huobiSign(signSb.toString(), secretKey);
        return urlEncode(s);
    }

    /**
     * 火币时间戳获取
     * @return
     */
    public static String getTimestamp () {
        return Instant.ofEpochSecond(Instant.now().getEpochSecond()).atZone(ZoneId.of("Z")).format(HUOBI_TIME_STAMP_FORMAT);
    }

    /**
     * 请求URL获取
     * @param path 接口路径
     * @return
     */
    public static String getRequestUrl (String path) {
        return NETWORK_PROTOCOL + DOMAIN + path;
    }

    /**
     * 使用标准URL Encode编码。注意和JDK默认的不同，空格被编码为%20而不是+。
     *
     * @param s String字符串
     * @return URL编码后的字符串
     */
    public static String urlEncode (String s) {
        try {
            return URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            log.error("URL encoder 异常", e);
            throw new TransactionException("币夫下单失败");
        }
    }

    /**
     * 获取精度
     * @param symbol
     * @param type 1量(btc) 2价(usdt)
     * @return
     */
    public static int getScale (String symbol, int type) {
        if (StringUtils.isBlank(symbol)) {
            throw new TransactionException("交易对不能为空");
        }
        HuobiSymbolEnum symbolEnum = HuobiSymbolEnum.getBySymbol(symbol);
        if (1 == type) {
            return symbolEnum.getNumScale();
        } else if (2 == type) {
            return symbolEnum.getPriceScale();
        } else {
            throw new TransactionException("类型异常");
        }
    }

    private static Integer getOrderStatus(String orderState) {
        Integer status = null;
        switch (orderState) {
            case "submitted":
                status = BourseOrder.Status.PUBLISHED.value();
                break;
            case "partial-filled":
                status = BourseOrder.Status.DEAL_PART.value();
                break;
            case "partial-canceled":
                status = BourseOrder.Status.CANCEL_PART.value();
                break;
            case "filled":
                status = BourseOrder.Status.DEALED.value();
                break;
            case "canceled":
                status = BourseOrder.Status.CANCLED.value();
                break;
            case "created":
                status = BourseOrder.Status.PUBLISHED.value();
                break;
            default:
        }
        return status;
    }

    /**
     * 测试使用
     */
    private static class HuobiWebSocketClient extends WebSocketClient {

        /**
         * 火币websocket请求地址 aws云服务器推荐使用 wss://api-aws.huobi.pro/ws
         */
        private static final String HUOBI_WEBSOCKET_URL = "wss://api.huobi.pro/ws";

        /**
         * 此主题提供24小时内最新市场概要快照。快照频率不超过每秒10次。
         */
        private static final String MARKET_TOPIC = "market.%s.detail";

        private static final String SUB_KEY = "sub";
        private static final String ID_KEY = "id";

        private static final String PING_NAME = "ping";
        private static final String PONG_NAME = "pong";
        private static final String TICK_NAME = "tick";

        public HuobiWebSocketClient(URI serverUri, Draft protocolDraft, Map<String, String> httpHeaders, int connectTimeout) {
            super(serverUri, protocolDraft, httpHeaders, connectTimeout);
        }

        @Override
        public void onOpen(ServerHandshake handshakedata) {
            log.info("火币市场概要连接成功");
            JSONObject json = new JSONObject();
            // 测试暂时用btcusdt 1
            json.put(SUB_KEY, String.format(MARKET_TOPIC, "btcusdt"));
            json.put(ID_KEY, 1);
            this.send(json.toJSONString());
        }

        @Override
        public void onMessage(String message) {
            log.info("收到来自火币的消息(String)：{}", message);
        }

        /**
         * WebSocket API 返回的所有数据都进行了 GZIP 压缩，需要 client 在收到数据之后解压。
         * @param byteBuffer
         */
        @Override
        public void onMessage(ByteBuffer byteBuffer) {
            byte[] array = byteBuffer.array();
            array = HuoBiGZipUtils.decompress(array);
            String str = new String(array, StandardCharsets.UTF_8);
            log.info("收到来自火币的消息：{}", str);
            if (str.contains(PING_NAME)) {
                this.send(str.replace(PING_NAME, PONG_NAME));
            }else if (str.contains(TICK_NAME)) {
                JSONObject json = JSON.parseObject(str).getJSONObject(TICK_NAME);
                //最新价
                BigDecimal close = json.getBigDecimal("close");
                //开盘价
                BigDecimal open = new BigDecimal("9138.18");
                log.info("获取到最新价：{}， 开盘价 ：{}", close, open);
                BigDecimal v = close.subtract(open).divide(open, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                log.info("涨幅:{}%", v);
            }else {
                log.warn("火币WebSocket数据：" + str + "，未做任何处理。");
            }
        }

        @Override
        public void onError(Exception e) {
            log.error("火币WebSocket接口，发生异常", e);
        }

        @Override
        public void onWebsocketPing(WebSocket conn, Framedata f) {
            log.warn("onWebsocketPing 获取到火币WebSocket的心跳信息。注意：我们没有处理对该信息做任何处理，请查看会不会对我们的服务造成影响");
        }

        @Override
        public void onWebsocketPong(WebSocket conn, Framedata f) {
            log.warn("onWebsocketPong 获取到火币WebSocket的心跳信息。注意：我们没有处理对该信息做任何处理，请查看会不会对我们的服务造成影响");
        }

        @Override
        public void onClose(int status, String msg, boolean arg2) {
            log.info("火币WebSocket接口已关闭，原因：{} , 状态：{} ", msg, status);
//            try {
//
//                // 重新连接（10秒后）
//                if (!isDestroy) {
//                    reconnectTimer.schedule(new TimerTask() {
//                        @Override
//                        public void run() {
//                            reconnect();
//                            // 取消任务
//                            this.cancel();
//                            // 清空已取消的任务
//                            reconnectTimer.purge();
//                        }
//                    }, reconnectDelay);
//                }
//            }catch (Exception e) {
//                log.info("火币WebSocket接口，关闭发生异常",e);
//            }
        }
    }

}
